package com.crazymaker.springcloud.seckill.idGenerator;

import com.crazymaker.springcloud.common.distribute.idGenerator.IdService;
import com.crazymaker.springcloud.standard.basicFacilities.CustomAppContext;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IncrementGenerator;

import java.io.Serializable;

/**
 * hibernate 的自定义ID生成器
 */
public class SeckillOrderIdentityGenerator extends IncrementGenerator
{
    /**
     * 生成ID
     */
    @Override
    public Serializable generate(SharedSessionContractImplementor sessionImplementor, Object object) throws HibernateException
    {
        Serializable id = null;
        /**
         * 调用自定义的snowflake 算法，结合Zookeeper 生成ID
         */
        IdService idService = (IdService) CustomAppContext.getBean("seckillOrderIdentityGenerator" );
        if (null != idService)
        {
            id = idService.nextId();
            return id;
        }

        id = sessionImplementor.getEntityPersister(null, object)
                .getClassMetadata().getIdentifier(object, sessionImplementor);
        return id != null ? id : super.generate(sessionImplementor, object);
    }
}
